package org.huatek.anders.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author anders
 * @date 2018-11-17 18:53
 **/
@ServerEndpoint(value = "/websocket")
@Component
@Slf4j
public class WebSocketServerEndpoint {
    /**
     * 存活的session集合（使用线程安全的map保存）
     */
    private static Map<String, Session> livingSessions = new ConcurrentHashMap<>();

    /**
     * 建立连接的回调方法
     *
     * @param session 与客户端的WebSocket连接会话
     */
    @OnOpen
    public void onOpen(Session session) {
        livingSessions.put(session.getId(), session);
        log.info("进入连接，当前连接数："+livingSessions.size());
    }

    /**
     * 客户端发送消息
     * @param message 消息
     * @param session 客户端session
     * @param userId 客户端业务用户id
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("userId") String userId) {
        log.info(userId + " : " + message);
        sendMessageToAll(userId + " : " + message);
    }


    @OnError
    public void onError(Session session, Throwable error) {
        log.error(session.getId()+"：发生错误", error);
    }


    @OnClose
    public void onClose(Session session) {
        livingSessions.remove(session.getId());
        log.info("关闭连接，当前连接数："+livingSessions.size());
    }

    /**
     * 单独发送消息
     */
    public void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            log.error("发送消息失败", e);
        }
    }

    /**
     * 群发消息
     */
    public void sendMessageToAll(String message) {
        //ObjectMapper objectMapper = new ObjectMapper();
        //MqMessageEntity mqMessageEntity = objectMapper.readValue(message, MqMessageEntity.class)
        livingSessions.forEach((sessionId, session) -> { sendMessage(session, message); });
    }

}
